/*
 *  Copyright 2019-2020 Zheng Jie
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package me.zhengjie.modules.cspimp.psp.service.impl;

import me.zhengjie.modules.cspimp.psp.domain.TargetResponsibility;
import me.zhengjie.modules.cspimp.psp.domain.vo.TargetResponsibilityVo;
import me.zhengjie.modules.system.domain.Dept;
import me.zhengjie.modules.system.domain.User;
import me.zhengjie.modules.system.repository.DeptRepository;
import me.zhengjie.modules.system.repository.UserRepository;
import me.zhengjie.utils.*;
import lombok.RequiredArgsConstructor;
import me.zhengjie.modules.cspimp.psp.repository.TargetResponsibilityRepository;
import me.zhengjie.modules.cspimp.psp.service.TargetResponsibilityService;
import me.zhengjie.modules.cspimp.psp.service.dto.TargetResponsibilityDto;
import me.zhengjie.modules.cspimp.psp.service.dto.TargetResponsibilityQueryCriteria;
import me.zhengjie.modules.cspimp.psp.service.mapstruct.TargetResponsibilityMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.util.CollectionUtils;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;

/**
 * @author zmm
 * @website https://docs.auauz.net
 * @description 服务实现
 * @date 2020-05-31
 **/
@Service
@RequiredArgsConstructor
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class TargetResponsibilityServiceImpl implements TargetResponsibilityService {

    private final TargetResponsibilityRepository targetResponsibilityRepository;
    private final TargetResponsibilityMapper targetResponsibilityMapper;
    private final DeptRepository deptRepository;
    private final UserRepository userRepository;

    @Override
    public Map<String, Object> queryAll(TargetResponsibilityQueryCriteria criteria, Pageable pageable) {
        List<TargetResponsibility> page = targetResponsibilityRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder));
        List<TargetResponsibilityDto> targetResponsibilityList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(page)) {
            for (TargetResponsibility targetResponsibility : page) {
                TargetResponsibilityDto targetResponsibilityDto = new TargetResponsibilityDto();
                BeanUtils.copyProperties(targetResponsibility, targetResponsibilityDto);
                User user = userRepository.findById(targetResponsibility.getDutyUserId()).orElse(null);

                if (null!=user) {
                    targetResponsibilityDto.setUsername(user.getUsername());
                }
                Dept dept = deptRepository.findById(targetResponsibility.getDutyDeptId()).orElse(null);
                if (null!=dept) {
                    System.err.println("sdsdsdsdsdsds");
                    targetResponsibilityDto.setDeptName(dept.getName());
                }
                targetResponsibilityList.add(targetResponsibilityDto);

            }
        }
        return PageUtil.toPage(PageUtil.listPage(targetResponsibilityList, pageable));
    }

    @Override
    public List<TargetResponsibilityDto> queryAll(TargetResponsibilityQueryCriteria criteria) {
        return targetResponsibilityMapper.toDto(targetResponsibilityRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)));
    }

    @Override
    public TargetResponsibilityDto findById(Long id) {
        TargetResponsibility targetResponsibility = targetResponsibilityRepository.findById(id).orElseGet(TargetResponsibility::new);
        ValidationUtil.isNull(targetResponsibility.getId(), "TargetResponsibility", "id", id);
        TargetResponsibilityDto targetResponsibilityDto = new TargetResponsibilityDto();
        BeanUtils.copyProperties(targetResponsibility, targetResponsibilityDto);
        User user = userRepository.findById(targetResponsibility.getDutyUserId()).get();
        if (null != user) {
            targetResponsibilityDto.setUsername(user.getUsername());
        }
        Dept dept = deptRepository.findById(targetResponsibility.getDutyDeptId()).get();
        if (null != dept) {
            targetResponsibilityDto.setDeptName(dept.getName());
        }
        return targetResponsibilityMapper.toDto(targetResponsibility);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public TargetResponsibilityDto create(TargetResponsibilityVo resources) {
        TargetResponsibility targetResponsibility = new TargetResponsibility();
        BeanUtils.copyProperties(resources, targetResponsibility);
        targetResponsibility.setCid(0l);
//        Date formulateDate = null, auditDate = null, approvalDate = null;
//        try {
//            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//            formulateDate = sf.parse(resources.getFormulateDate());
//            auditDate = sf.parse(resources.getAuditDate());
//            approvalDate = sf.parse(resources.getApprovalDate());
//        } catch (Exception e) {
//        }
//        targetResponsibility.setApprovalDate(new Timestamp(approvalDate.getTime()));
//        targetResponsibility.setAuditDate(new Timestamp(auditDate.getTime()));
//        targetResponsibility.setFormulateDate(new Timestamp(formulateDate.getTime()));
        targetResponsibilityRepository.save(targetResponsibility);
        return targetResponsibilityMapper.toDto(targetResponsibility);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(TargetResponsibilityVo resources) {
        TargetResponsibility targetResponsibility = targetResponsibilityRepository.findById(resources.getId()).orElseGet(TargetResponsibility::new);
        ValidationUtil.isNull(targetResponsibility.getId(), "TargetResponsibility", "id", resources.getId());
        BeanUtils.copyProperties(resources, targetResponsibility);
        Date formulateDate = null, auditDate = null, approvalDate = null;
        try {
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            if (StringUtils.isNotBlank(resources.getApprovalDate())) {
                approvalDate = sf.parse(resources.getApprovalDate());
                targetResponsibility.setApprovalDate(new Timestamp(approvalDate.getTime()));

            }
            if (StringUtils.isNotBlank(resources.getAuditDate())) {
                auditDate = sf.parse(resources.getAuditDate());
                targetResponsibility.setAuditDate(new Timestamp(auditDate.getTime()));

            }
            if (StringUtils.isNotBlank(resources.getFormulateDate())) {
                formulateDate = sf.parse(resources.getFormulateDate());
                targetResponsibility.setFormulateDate(new Timestamp(formulateDate.getTime()));

            }
        } catch (Exception e) {
            e.getMessage();
        }
        targetResponsibilityRepository.save(targetResponsibility);
    }

    @Override
    public void deleteAll(Long[] ids) {
        for (Long id : ids) {
            targetResponsibilityRepository.deleteById(id);
        }
    }

    @Override
    public void download(List<TargetResponsibilityDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (TargetResponsibilityDto targetResponsibility : all) {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("创建者", targetResponsibility.getCreateBy());
            map.put("更新者", targetResponsibility.getUpdateBy());
            map.put("创建日期", targetResponsibility.getCreateTime());
            map.put("更新时间", targetResponsibility.getUpdateTime());
            map.put("责任级别", targetResponsibility.getDutyLevel());
            map.put("责任名称", targetResponsibility.getDutyName());
            map.put("责任人", targetResponsibility.getDutyUserId());
            map.put("责任部门", targetResponsibility.getDutyDeptId());
            map.put("责任目标", targetResponsibility.getDutyTarget());
            map.put("责任描述", targetResponsibility.getDutyDesc());
            map.put("文件路径", targetResponsibility.getFilePath());
            map.put("制定日期", targetResponsibility.getFormulateDate());
            map.put("审核日期", targetResponsibility.getAuditDate());
            map.put("批准日期", targetResponsibility.getApprovalDate());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
}